'use strict';

module.exports = (options, app) => {
  return async function accessLog(ctx, next) {
    // 记录请求开始时间
    const startTime = Date.now();
    
    // 获取客户端IP
    const clientIP = ctx.request.ip || ctx.headers['x-forwarded-for'] || 'unknown';
    
    // 获取User-Agent
    const userAgent = ctx.headers['user-agent'] || 'unknown';
    
    // 记录请求信息
    app.logger.info('[access] %s %s from %s, query: %s, body: %s, user-agent: %s', 
      ctx.method, 
      ctx.url,
      clientIP,
      JSON.stringify(ctx.query),
      JSON.stringify(ctx.request.body),
      userAgent
    );

    try {
      // 执行后续中间件和路由处理
      await next();
    } catch (err) {
      // 记录异常
      app.logger.error('[access-error] %s %s %s %s ms, ip: %s, error: %s', 
        ctx.method, 
        ctx.url, 
        ctx.status,
        Date.now() - startTime,
        clientIP,
        err.message
      );
      throw err;
    }

    // 记录响应信息和耗时
    const duration = Date.now() - startTime;
    
    // 将访问日志存储到数据库（通过service层）
    try {
      await ctx.service.accessLog.create({
        method: ctx.method,
        url: ctx.url,
        query: ctx.query,
        body: ctx.request.body,
        ip: clientIP,
        userAgent: userAgent,
        responseStatus: ctx.status,
        responseTime: duration
      });
    } catch (err) {
      app.logger.error('Failed to save access log to database: %s', err.message);
    }

    app.logger.info('[access-response] %s %s %s %s ms, ip: %s, response-size: %s bytes', 
      ctx.method, 
      ctx.url, 
      ctx.status,
      duration,
      clientIP,
      JSON.stringify(ctx.body || ctx.response.body || '').length
    );
  };
};